<template>
  <el-drawer
    :title="$t('message.videogl')"
    :visible.sync="isShowModal"
    size="60%"
    :before-close="handleClose"
  >
    <div class="area-space-box">
      <div class="box-item area">
        <el-button
          v-preventReClick
          class="add-area"
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="toAddArea"
        >{{ $t('message.tijia') }}</el-button>
        <div class="item-title">{{ $t('message.spml') }}</div>
        <div
          v-for="item in areaListData"
          :key="item.id"
          :class="
            activeCheckArea.id === item.id ? 'left-item active' : 'left-item'
          "
          @click="showThisSpace(item)"
        >
          <div class="flex-cb title-buttons">
            <div class="title">{{ item.name }}</div>
            <div class="flex-c buttons">
              <el-button
                v-preventReClick
                type="success"
                size="small"
                @click.stop="toEditArea(item)"
              >{{ $t('message.bjml') }}</el-button>
              <el-button
                v-preventReClick
                type="danger"
                size="small"
                @click.stop="toDeleteArea(item.id)"
              >{{ $t('message.del') }}</el-button>
            </div>
          </div>
        </div>
        <div class="flex-cc doumee-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="areaTotal"
            :current-page.sync="pagination.page"
            :page-size="5"
            hide-on-single-page
            @current-change="toGetAreaList"
          />
        </div>
        <Paginations
          :total="areaTotal"
          :page-size="pagination.rows"
          :page="pagination.page"
          :integrated="integrated"
          @current-change="toGetAreaList"
        />
      </div>
      <!-- 右边列表 -->
      <div class="box-item space">
        <el-button
          v-if="activeCheckArea.id"
          v-preventReClick
          class="add-area"
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="toAddSpace(activeCheckArea)"
        >{{ $t('message.tijia') }}</el-button>
        <div class="item-title">{{ $t('message.mlsp') }}</div>
        <div v-for="item in spaceListData" :key="item.id" class="area-item">
          <div class="flex-cb title-buttons">
            <div class="title">{{ item.name }}</div>
            <div class="flex-c buttons">
              <el-button v-preventReClick type="success" size="small" @click="toEditSpace(item)">{{ $t('message.bjsp2') }}</el-button>
              <el-button
                v-preventReClick
                type="danger"
                size="small"
                @click.stop="courseVideoDel(item.id)"
              >{{ $t('message.del') }}</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增/编辑目录 -->
    <el-dialog
      append-to-body
      :title="areaAddEdit ? $t('message.bjml') : $t('message.xzml')"
      :visible.sync="showAddArea"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      @closed="cancelAddEditArea"
    >
      <el-form ref="mlform" :model="addAreaForm" label-width="auto" :rules="rules" label-suffix="：">
        <el-form-item :label="$t('message.mlmc')" prop="name">
          <el-input v-model="addAreaForm.name" :placeholder="$t('message.qsr') + $t('message.mlmc')" maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('message.sort')" prop="sortNum">
          <el-input v-model="addAreaForm.sortNum" :placeholder="$t('message.qsr') + $t('message.sort')" maxlength="4" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddEditArea">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick type="primary" @click="confirmAddArea">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑视频 -->
    <el-dialog
      append-to-body
      :title="spaceAddEdit ? $t('message.bjsp2') : $t('message.xzsp2')"
      :visible.sync="showAddSpace"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      @closed="cancelAddEditSpace"
    >
      <el-form ref="ruleForm" :model="addSpaceForm" label-width="auto" :rules="ruleb" label-suffix="：">
        <el-form-item :label="$t('message.spmc2')" prop="name">
          <el-input
            v-model="addSpaceForm.name"
            maxlength="50"
            :placeholder="$t('message.qsr') + $t('message.spmc2')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.scsp')" prop="url">
          <el-upload
            class="upload-demo"
            :action="uploadFileUrl"
            :data="uploadData"
            :limit="1"
            accept=".avi,.mpg,.mpeg,.mp4"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="uploadSuccess"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">{{ $t('message.djsc') }}</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddEditSpace">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick type="primary" @click="confirmAddSpace">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
  </el-drawer>
</template>

<script>
// import { parseTime } from '@/utils/index'
import store from '@/store'
import { courseVideoList, uploadFile, courseVideoSave, courseVideoDel, courseDirectory, addVideoList, deleteVideoList } from '@/api'
export default {
  name: 'OnlineCoursesVideoOrder',
  data() {
    return {
      isShowModal: false,
      modalDialog: store.getters.dialog,
      meta: [],
      uploadFileUrl: uploadFile,
      venueId: sessionStorage.getItem('venueId'),
      areaListData: [],
      spaceListData: [],
      pagination: {
        page: 1,
        rows: 5,
        firstQueryTime: ''
      },
      areaTotal: 0,
      spacePagination: {
        page: 1,
        rows: 5
        // firstQueryTime: parseTime(new Date())
      },
      activeCheckArea: {},
      areaAddEdit: false,
      spaceAddEdit: false,
      showAddArea: false,
      addAreaForm: {},
      showAddSpace: false,
      addSpaceForm: {},
      uploadData: {
        folder: 'COURSE_IMG',
        type: ''
      },
      integrated: false,
      fileList: [],
      courseId: '',
      rules: {
        name: [{ required: true, message: this.$t('message.qsr') + this.$t('message.mlmc'), trigger: 'blur' }],
        sortNum: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.sort'), trigger: 'blur', pattern: /^[1-9]{1}[0-9]*$|^0{1}\.{1}[0-9]+$|^[1-9]{1}[0-9]*\.{1}[0-9]+$/ }
        ]
      },
      ruleb: {
        name: [{ required: true, message: this.$t('message.qsr') + this.$t('message.spmc2'), trigger: 'blur' }],
        url: [{ required: true, message: this.$t('message.qsc') + this.$t('message.video'), trigger: 'change' }]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    // this.courseId = this.$route.query.courseId
    // this.toGetAreaList()
  },
  methods: {
    handleClose() {
      this.isShowModal = false
      this.$emit('close')
    },
    handleRemove(file, fileList) {
      this.$set(this.addSpaceForm, 'video', '')
      this.$set(this.addSpaceForm, 'url', '')
    },
    beforeRemove(file, fileList) {
      return this.$confirm(this.$t('message.qryc') + ` ${file.name}？`)
    },
    // 上传成功
    uploadSuccess(res, file, fileList) {
      if (res.success) {
        this.$set(this.addSpaceForm, 'video', res.showUrl)
        this.$set(this.addSpaceForm, 'url', res.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || this.$t('message.scsb'))
      }
    },
    // 获取列表
    toGetAreaList(page) {
      const { pagination, venueId } = this
      if (page) {
        this.pagination.page = page
        pagination.page = page
      }
      courseDirectory({ pagination, param: { venueId, courseId: this.courseId }})
        .then(res => {
          this.areaListData = res.recordList
          this.areaTotal = res.totalCount
        })
    },
    toEditArea(e) {
      this.areaAddEdit = true
      this.showAddArea = true
      this.addAreaForm = {
        name: e.name,
        sortNum: e.rank,
        id: e.id
      }
    },
    // 新增目录
    toAddArea() {
      this.areaAddEdit = false
      this.showAddArea = true
      this.addAreaForm = {}
    },
    // 取消新增/编辑
    cancelAddEditArea() {
      this.showAddArea = false
      this.addAreaForm = {}
    },
    // 确认新增/编辑
    confirmAddArea() {
      const { areaAddEdit, courseId } = this
      const param = this.addAreaForm
      this.$refs.mlform.validate((valid) => {
        if (valid) {
          param.courseId = courseId
          param.sortNum = Number(param.sortNum)
          addVideoList({ param })
            .then(res => {
              this.$message.success(areaAddEdit ? this.$t('message.editcg') : this.$t('message.addcg'))
              this.showAddArea = false
              this.toGetAreaList()
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除目录
    toDeleteArea(id) {
      this.$confirm(this.$t('message.scmltc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          deleteVideoList({ param: { id, courseId: this.courseId }})
            .then(res => {
              if (res.errorCode !== '000000') return
              this.$message.success(this.$t('message.delcg'))
              this.toGetAreaList()
              this.activeCheckArea = false
              this.spaceListData = []
            })
        })
        .catch(() => {
          // this.$message.info('已取消删除')
        })
    },
    // 展示某场区的场地
    showThisSpace(area) {
      this.activeCheckArea = area
      this.getSpaceList(1)
    },
    // 获取某目录列表
    getSpaceList() {
      const { activeCheckArea } = this
      courseVideoList({ param: { directoryId: activeCheckArea.id, courseId: this.courseId }})
        .then(res => {
          this.spaceListData = res.recordList || []
        })
    },
    // 新增场地
    toAddSpace(area) {
      this.showAddSpace = true
      this.addSpaceForm = {}
      this.fileList = []
      this.spaceAddEdit = false
      this.activeCheckArea = area
      this.getSpaceList(1)
    },
    // 编辑场地
    toEditSpace(space) {
      this.addSpaceForm = space
      this.fileList = [{
        url: space.urlAll,
        name: space.name
      }]
      this.showAddSpace = true
      this.spaceAddEdit = true
    },
    // 取消新增/编辑场地
    cancelAddEditSpace() {
      this.showAddSpace = false
    },
    // 确认新增/编辑场地
    confirmAddSpace() {
      const { addSpaceForm, activeCheckArea, spaceAddEdit, spaceListData } = this
      const param = {}
      const that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          spaceListData.forEach((e, index) => {
            if (e.id === addSpaceForm.id) {
              spaceListData.splice(index, 1)
            }
          })
          spaceListData.push(addSpaceForm)
          param.courseId = that.courseId
          param.directoryId = activeCheckArea.id
          param.list = spaceListData
          courseVideoSave({ param })
            .then(res => {
              this.$emit('success')
              this.handleClose()
              if (spaceAddEdit) {
                that.$message.success(this.$t('message.addcg'))
              } else {
                that.$message.success(this.$t('message.editcg'))
              }
              that.showAddSpace = false
              that.toGetAreaList()
              that.getSpaceList()
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除场地
    courseVideoDel(id) {
      this.$confirm(this.$t('message.scsptc2'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      }).then(() => {
        courseVideoDel({ param: { id }})
          .then(res => {
            this.$message.success(this.$t('message.delcg'))
            this.getSpaceList()
            this.toGetAreaList()
          })
      }).catch(() => {
        // this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.area-space-box {
  display: flex;
  position: relative;
  &::after {
    content: '';
    display: block;
    position: absolute;
    height: 100%;
    width: 1px;
    top: 0;
    left: 50%;
    transform: translate(-50%);
    background-color: #ccc;
  }
  .add-area {
    position: absolute;
    top: 0;
    right: 30px;
  }
  .box-item {
    flex: 1;
    position: relative;
    .item-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 30px;
      line-height: 30px;
    }
  }
  .box-item.area {
    padding-right: 30px;
  }
  .box-item.space {
    padding-left: 30px;
  }
  .left-item {
    background-color: #f7f7f7;
    padding: 20px;
    text-align: center;
    border-radius: 4px;
    margin-top: 20px;
    flex-direction: column;
    cursor: pointer;
    white-space: nowrap;
    text-overflow: ellipsis;
    -webkit-text-overflow: ellipsis;
    overflow: hidden;
    .title {
      line-height: 50px;
    }
  }
  .area-item {
    background-color: #f7f7f7;
    padding: 20px;
    border-radius: 4px;
    margin-top: 20px;
    cursor: pointer;
    .title-buttons {
      margin-bottom: 20px;
    }
    .title {
      font-size: 17px;
      font-weight: bold;
    }
  }
  .left-item.active,
  .area-item.active {
    box-shadow: 0 0 0 1px $menuActive;
    background-color: #f4f7fc;
  }
}
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
